import { useTagsViewStoreWithOut } from '@/store/modules/tagsView'
import { RouteLocationNormalizedLoaded, useRouter } from 'vue-router'
import { computed, nextTick, unref } from 'vue'
import { usePermissionStore } from '@/store/modules/permission'

export const useTagsView = () => {
  const tagsViewStore = useTagsViewStoreWithOut()

  const { replace, currentRoute, push } = useRouter()

  const selectedTag = computed(() => tagsViewStore.getSelectedTag)

  const closeAll = (callback?: Fn) => {
    tagsViewStore.delAllViews()
    callback?.()
  }

  const closeLeft = (callback?: Fn) => {
    tagsViewStore.delLeftViews(unref(selectedTag) as RouteLocationNormalizedLoaded)
    callback?.()
  }

  const closeRight = (callback?: Fn) => {
    tagsViewStore.delRightViews(unref(selectedTag) as RouteLocationNormalizedLoaded)
    callback?.()
  }

  const closeOther = (callback?: Fn) => {
    tagsViewStore.delOthersViews(unref(selectedTag) as RouteLocationNormalizedLoaded)
    callback?.()
  }

  const closeCurrent = (view?: RouteLocationNormalizedLoaded, callback?: Fn) => {
    if (view?.meta?.affix) return
    tagsViewStore.delView(view || unref(currentRoute))

    callback?.()
  }

  const refreshPage = async (view?: RouteLocationNormalizedLoaded, callback?: Fn) => {
    tagsViewStore.delCachedView()
    const { path, query } = view || unref(currentRoute)
    await nextTick()
    replace({
      path: '/redirect' + path,
      query: query
    })
    callback?.()
  }

  const setTitle = (title: string, path?: string) => {
    tagsViewStore.setTitle(title, path)
  }
  // 是否是当前tag
  const isActive = (route: RouteLocationNormalizedLoaded): boolean => {
    return route.path === unref(currentRoute).path
  }
  // 新增tag
  const addTags = () => {
    const { name } = unref(currentRoute)
    if (name) {
      tagsViewStore.addView(unref(currentRoute))
    }
    return false
  }
  // 关闭当前的tag
  const closeSelectedTag = () => {
    const view = unref(currentRoute)

    if (!view) return

    tagsViewStore.delView(view)
    if (isActive(view)) {
      toLastView()
    }
  }
  const permissionStore = usePermissionStore()

  // 跳转到最后一个
  const toLastView = () => {
    const visitedViews = tagsViewStore.getVisitedViews
    const latestView = visitedViews.slice(-1)[0]
    if (latestView) {
      push(latestView)
    } else {
      if (
        unref(currentRoute).path === permissionStore.getAddRouters[0].path ||
        unref(currentRoute).path === permissionStore.getAddRouters[0].redirect
      ) {
        addTags()
        return
      }
      // TODO: You can set another route
      push('/')
    }
  }

  return {
    closeAll,
    closeLeft,
    closeRight,
    closeOther,
    closeCurrent,
    refreshPage,
    setTitle,
    closeSelectedTag
  }
}
